import {
	defineStore
} from 'pinia'
import {
	Logout,
	RemovePushId,
	UpdateCancelState
} from '@/api/modules/system'

// #ifdef APP-PLUS
const qiyuModule = uni.requireNativePlugin("Netease-QiyuModule")
// #endif
// #ifdef H5
import YSF from '@neysf/qiyu-web-sdk';
// #endif


const GlobalStore = defineStore('__GLOBAL_STORE', {
	unistorage: true,
	state: () => ({
		userInfo: null,
		token: "",
		activeAddress: {},
		activeMyTicket: {},
		wandanCard: {},
		acceptanceCard: {},
		registerID: "",
		groupid: '',
		ysfFn: null,
		receiveSearchVal: "",
		tabbarIdx: 1,
		jumpType: 0,
		activeMall: {},
		isReadItem: {},
		refreshInterval: null
	}),
	actions: {
		//	type：update：更新注销状态
		login(res, type) {
			if (!res?.userInfo && !res?.token) {
				return
			}

			// __FIRST_OPEN 用于区分是APP 启动加载还是页面返回
			uni.setStorageSync("__FIRST_OPEN", 1)
			//	__DEFAULT_LOGIN_PHONE  用于填写登录页默认手机号
			uni.setStorageSync("__DEFAULT_LOGIN_PHONE", res?.userInfo.phone)

			this.userInfo = res?.userInfo
			this.token = res?.token
			//	更新注销状态使用
			if (type === "update") {
				UpdateCancelState({
					id: res?.userInfo.id,
					isDelete: 0
				}).then(res => {
					uni.reLaunch({
						url: '/components/xzy-frame/index',
					});
				})
			} else {
				uni.reLaunch({
					url: '/components/xzy-frame/index',
				});
			}

		},
		logout(type) {
			RemovePushId({
				registrationId: this.registerID
			}).then(res => {
				Logout().then(res => {
					uni.removeStorageSync('BLACK_DIALOG')

					// #ifdef APP-PLUS
					qiyuModule.logout()
					// #endif
					if (this.ysfFn) {
						this.ysfFn('logoff')
					}
					this.token = null
					this.userInfo = null
					if (!type) {
						uni.reLaunch({
							url: '/pages/login/index'
						});
					}
				})
			})
		},
		setIsReadItem(item) {
			this.isReadItem = item
		},
		clearLoginInfo() {
			this.token = null
			this.userInfo = null
			uni.reLaunch({
				url: '/pages/login/index'
			});
		},
		setUserInfo(info) {
			this.userInfo = info
		},
		//	保存选中地址 背包实物领取, 大转盘实物领取使用
		setActiveAddress(item) {
			this.activeAddress = item
		},
		//	保存商城优惠券
		setActiveMyTicket(item) {
			this.activeMyTicket = item
		},
		// 保存完单卡图片和钱   抢单时使用
		setWandanCard(item) {
			this.wandanCard = item
		},
		// 保存验收卡  上传验收用
		setAcceptanceCard(item) {
			this.acceptanceCard = item
		},
		//	极光推送使用 设备Id
		setRegisterID(id) {
			console.log(id, 'registerID');
			this.registerID = id
		},
		// //	设置是否含有sim卡，一键登录使用
		// setSimStatus(status){
		// 	this.isSim = status
		// },
		// 设置他发布的跳转检索参数
		setReceiveSearchVal(val) {
			this.receiveSearchVal = val
		},
		//	设置tabbar选中项，用于区分页面接口调用
		setTabbarIdx(val) {
			this.tabbarIdx = val
		},
		//	从年卡跳转协议 为了解决跳转协议中心后返回回来又重新调一遍接口页面显示还是年卡但是显示的是周卡的钱
		setJumpType(val) {
			this.jumpType = val
		},
		//保存商品使用
		setMallInfo(val) {
			this.activeMall = val
		},
		//保存groupid  打开H5客服弹窗
		setOpenQiyuH5(val) {
			YSF.init('b2d907bb833c0d14c44c9ac98e153e24', {
				hidden: true
			}).then(ysf => {
				this.ysfFn = ysf
				ysf('config', {
					groupid: val,
					uid: this.userInfo.id,
					name: this.userInfo.userName,
					mobile: this.userInfo.phone,
					email: this.userInfo.code,
					data: JSON.stringify([{
							"key": "real_name",
							"value": this.userInfo.userName
						},
						{
							"key": "mobile_phone",
							"value": this.userInfo.phone
						},
						{
							"key": "avatar",
							"value": this.userInfo.photo
						},
						{
							"key": "email",
							"value": this.userInfo.code
						},
					]),
					success: function() {
						console.log('客户信息上报成功');
						ysf('open');
					},
					error: function() {
						console.log('客户信息上报失败');
					}
				});
			}).catch(error => {
				console.log('sdk加载失败---', error);
			});
		},
		//打开app安卓客服弹窗
		setOpenQiyuAPP(val) {
			qiyuModule.setUserInfo({
				userId: this.userInfo.id,
				name: this.userInfo.userName,
				mobile: this.userInfo.phone,
				email: this.userInfo.code,
				data: JSON.stringify([{
						"key": "real_name",
						"value": this.userInfo.userName
					},
					{
						"key": "mobile_phone",
						"value": this.userInfo.phone
					},
					{
						"key": "email",
						"value": this.userInfo.code
					},
					{
						"key": "avatar",
						"value": this.userInfo.ossFilePreview + this.userInfo.photo
					},
				]),
			}, (ret) => {
				if (ret.code == 200) {
					qiyuModule.openServiceActivity({
						title: '天玩客服',
						source: {
							title: '平台客服',
							groupId: val,
							robotFirst: true
						}
					})
					qiyuModule.updateOptions({
						isMixSDK: true,
						isPullMessageFromServer: false,
						uiCustomization: {
							hideLeftName: true,
							hideLeftAvatar: false,
							isShowTitleAvatar: true,
							hideRightAvatar: false,
							rightAvatar: this.userInfo?.photo
						},
						statusBarNotificationConfig: {
							showBadge: false,
							titleOnlyShowAppName: true,
						}
					}, (url) => {
						//点击url的回调
						plus.runtime.openWeb(url)
					})
				} else {
					//失败
				}
			})
		}
	}
})

export default GlobalStore